const express = require('express');
const router = express.Router();
const connection = require('../database/connection');
const email = require('./sendmail.js');

router.post('/',async function (req,res){
    console.log("req.body:"+req.body.email)
    const mail = req.body.email;
    if (!mail) {
        return res.send('参数错误')
    } //email出错时或者为空时
    let code = parseInt(Math.random() * 1000000).toString(); //生成随机验证码
    code = pad(code,6);
    console.log(code);
    //发送邮件
    email.sendMail(mail, code, (state) => {
        console.log('sendmail:'+code);
        if (state) {
            res.send({'errcode':0});
        } else {
            res.send({'errcode':1});
        }

    })
    let sql = "replace into verificationcode(email,code) values(?,?)";
    let arg = [];
    arg.push(mail);
    arg.push(code);
    let db_res = await connection.dbQuery(sql,arg);

})

function pad(num,n){
    let  len = num.length;
    while(len<n){
        num = "0"+num;
        len++;
    }
    return num;
}
module.exports = router;